package blue.wireless.mic;

import java.net.DatagramSocket;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

public class MicThread {
	public byte[] buffer;
	public static DatagramSocket socket;
	AudioRecord recorder;

	private int sampleRate = 48000;
	private int channelConfig = AudioFormat.CHANNEL_IN_STEREO;    
	private int audioFormat = AudioFormat.ENCODING_PCM_16BIT;      
	int minBufSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);
	boolean status = true;
	

	public void startStreaming() {
		minBufSize += 2048;
		Handler mHandler = new Handler(Looper.getMainLooper());
			mHandler.postDelayed(new Runnable() {
				@Override
		 		public void run() {
		           byte[] buffer = new byte[minBufSize];
		           Log.d("VS","Buffer created of size " + minBufSize);
		           //DatagramPacket packet;

		           recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,sampleRate,channelConfig,audioFormat,minBufSize*10);
		           Log.d("VS", "Recorder initialized");

		           recorder.startRecording();
		           while(status == true) {
		        	   //reading data from MIC into buffer
		        	   minBufSize = recorder.read(buffer, 0, buffer.length);

		        	   //putting buffer in the packet
		        	   //packet = new DatagramPacket (buffer,buffer.length);
		        	   //socket.send(packet);
		        	   String transData = new String(buffer);
		        	   Main.getInstance().sendMessage(transData);
		        	   System.out.println("MinBufferSize: " +minBufSize);
		           }
				}
			}, 30);
			Looper.loop();
	}
	   
}